﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BulldogCMS.Core.Storage.Cache
{
    public class WebCache : IStorageCache
    {
        public Node GetNode(string nodePath)
        {
            return HttpContext.Current.Cache[nodePath] as Node;
        }

        public void SetNode(Node node)
        {
            HttpContext.Current.Cache[node.Path] = node;
        }

        public void RemoveNode(string nodePath)
        {
            HttpContext.Current.Cache.Remove(nodePath);
        }

        public IEnumerable<Node> GetSubNodes(string parentNodePath)
        {
            return HttpContext.Current.Cache[parentNodePath + "__childnodes"] as IEnumerable<Node>;
        }

        public void SetSubNodes(string parentNodePath, IEnumerable<Node> childNodes)
        {
            HttpContext.Current.Cache[parentNodePath + "__childnodes"] = childNodes;
        }

        public void RemoveSubNodes(string parentNodePath)
        {
            HttpContext.Current.Cache.Remove(parentNodePath + "__childnodes");
        }

        private string GetVersionKey(string language, int version)
        {
            return string.Format("({0},{1})", language, version);
        }

        public NodeVersion GetNodeVersion(string nodePath, string language, int version)
        {
            string cacheIdent = nodePath.TrimEnd('/') + this.GetVersionKey(language, version);
            return HttpContext.Current.Cache[cacheIdent] as NodeVersion;
        }

        public void SetNodeVersion(string nodePath, NodeVersion nodeVersion)
        {
            string cacheIdent = nodePath.TrimEnd('/') + this.GetVersionKey(nodeVersion.LanguageName, nodeVersion.VersionNumber);
            HttpContext.Current.Cache[cacheIdent] = nodeVersion;
        }
    }
}